package logic

import (
	"api/pkg"
	"context"
	"fmt"
	"user_srv/user"

	"api/internal/svc"
	"api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type RealNameLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewRealNameLogic(ctx context.Context, svcCtx *svc.ServiceContext) *RealNameLogic {
	return &RealNameLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *RealNameLogic) RealName(req *types.RealNameRequest) (resp *types.Response, err error) {
	// todo: 实名认证
	userId := l.ctx.Value("userId").(int)

	//查询用户是否已经实名认证
	name, err := l.svcCtx.UserSrv.FindRealName(l.ctx, &user.FindRealNameInfoRequest{
		UserId:  int64(userId),
		IdCared: req.Idcard,
	})
	if err != nil {
		return &types.Response{
			Code: -2,
			Msg:  "服务器错误",
			Data: nil,
		}, nil
	}

	fmt.Println("实名状态为", name.Secc)

	if name.Secc {
		return &types.Response{
			Code: 3,
			Msg:  "用户已实名",
			Data: nil,
		}, nil
	}

	//判断实名是否认证成功
	if !pkg.RealNameCheck(req.Realname, req.Idcard) {
		return &types.Response{
			Code: -1,
			Msg:  "认证失败",
			Data: nil,
		}, nil
	}
	//新增实名信息
	_, err = l.svcCtx.UserSrv.AddRealName(l.ctx, &user.AddRealNameRequest{
		UserId:   int64(userId),
		RealName: req.Realname,
		IdCared:  req.Idcard,
	})

	if err != nil {
		return &types.Response{
			Code: -1,
			Msg:  "服务器错误",
			Data: nil,
		}, nil
	}

	return &types.Response{
		Code: 0,
		Msg:  "认证成功",
		Data: nil,
	}, nil
}
